package com.kinon.ycjshop.view;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ycjshop.Constatus;
import com.kinon.ycjshop.R;
import com.kinon.ycjshop.sqlbean.BaseGoods;
import com.kinon.ycjshop.sqlbean.GoodsBean;
import com.kinon.ycjshop.sqlbean.UserBuyBean;
import com.kinon.ycjshop.tools.CustomDialog;
import com.kinon.ycjshop.tools.HttpTools;
import com.kinon.ycjshop.tools.MyShowDialog;
import com.kinon.ycjshop.tools.NetWorkUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;

//import android.util.Log;

/**
 * Created by luohao on 2017-07-26.
 */

public class UrgentSetActivity extends Activity implements View.OnClickListener {

    //自定义登陆广播Action
    public static final String LOGIN_ACTION = "ON_URGENT";
    private TextView tv_back;
    private TextView btn_urgentOn;
    private TextView btn_getGoods;
    private TextView btn_pushBuy;
    private TextView btn_clearBuy;
    private HttpTools httpTools = null;
    private String token;
    private boolean isLunch = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_urgentset_layout);
        initView();
    }

    private void initView() {
        tv_back = (TextView) findViewById(R.id.tv_back);
        btn_urgentOn = (TextView) findViewById(R.id.btn_urgentOn);
        btn_getGoods = (TextView) findViewById(R.id.btn_getGoods);
        btn_pushBuy = (TextView) findViewById(R.id.btn_pushBuy);
        btn_clearBuy = (TextView) findViewById(R.id.btn_clearBuy);

        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");

        if (Constatus.URGENT_TYPE) {
            btn_urgentOn.setText("关闭紧急模式");

        } else {
            btn_urgentOn.setText("开启紧急模式");
        }
        setOnclick();
    }

    private void setOnclick() {
        tv_back.setOnClickListener(this);
        btn_urgentOn.setOnClickListener(this);
        btn_getGoods.setOnClickListener(this);
        btn_pushBuy.setOnClickListener(this);
        btn_clearBuy.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.btn_urgentOn:
                urgentOn();
                break;
            case R.id.btn_getGoods:
                getGoods();
                break;
            case R.id.btn_pushBuy:  //上传购买记录
                pushBuy();
                break;
            case R.id.btn_clearBuy:
                clearSqlite(UserBuyBean.class, "是否清空本地购买记录");
                break;
        }
    }


    private void urgentOn() {
        if (Constatus.URGENT_TYPE) {
            Constatus.URGENT_TYPE = false;
            btn_urgentOn.setText("开启紧急模式");
            Toast.makeText(getApplicationContext(), "紧急模式已关闭",
                    Toast.LENGTH_SHORT).show();
        } else {
            Constatus.URGENT_TYPE = true;
            btn_urgentOn.setText("关闭紧急模式");
            Toast.makeText(getApplicationContext(), "请注意!紧急模式已开启!",
                    Toast.LENGTH_SHORT).show();
        }
        sendLoginBroadcast();
    }

    private void clearSqlite(final Class<?> cal, String msg) {
        CustomDialog dialog = new CustomDialog(UrgentSetActivity.this,
                msg, new CustomDialog.DialogClickListener() {
            @Override
            public void onDialogClick(int btn) {
                if (btn == 1) {
                    try {
                        DataSupport.deleteAll(cal);
                        Toast.makeText(getApplicationContext(), "清除成功",
                                Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "清除失败",
                                Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                }
            }
        });

        dialog.show();
    }

    /**
     * 获得取餐信息
     */
    private void getGoods() {
        network();
//        httpTools.getOrders();
        if (httpTools == null) {
            httpTools = new HttpTools(getApplicationContext());
        }
//        Log.e("lh", "token== "+token);
        httpTools.backupGetGoods(token, new JsonGetGoods());

    }

    /**
     * 上传购买记录
     */
    private void pushBuy() {
        network();
        if (httpTools == null) {
            httpTools = new HttpTools(getApplicationContext(), 60 * 1000);
        }

        ArrayList<UserBuyBean> userbuyList = (ArrayList<UserBuyBean>)
                DataSupport.where("submit=? ", "0").find(UserBuyBean.class, true);
//        Log.e("lh", "settleList.size "+orderList.size());

        if (userbuyList.size() <= 0) {
            Toast.makeText(getApplicationContext(), "本地未查询到没有提交的记录",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        Gson gson = new Gson();
        String data = gson.toJson(userbuyList);
        Log.e("lh", "userbuyList==" + data);

//        try {
//            int len= data.getBytes("UTF-8").length/1024;
//            Log.e("lh", "len== "+len +"kb" );
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        httpTools.backupdealCorder(token, data, userbuyList.size(), new JsonPushBuy());
    }

    /**
     * 网络判断
     */
    private void network() {
        if (NetWorkUtil.isNetwork(getApplicationContext()) == false) {
            btn_pushBuy.setClickable(true);
            Toast.makeText(getApplicationContext(), "当前网络不可用",
                    Toast.LENGTH_SHORT).show();
            return;
        }
    }

    //向整个应用发送登陆广播事件 ，局部广播，局部广播安全
    private void sendLoginBroadcast() {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(LOGIN_ACTION));
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }

    private class JsonGetGoods extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            super.onStart();
            MyShowDialog.showLoadingDialog(UrgentSetActivity.this, "数据获取中.");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
            Log.e("lh", "JsonGetGoods==" + response.toString());
            try {
                boolean code = response.getBoolean("code");
                if (code == true) {
                    Toast.makeText(getApplicationContext(), "获取商品信息成功",
                            Toast.LENGTH_SHORT).show();
                    //删除数据库表中的所有数据
                    DataSupport.deleteAll(GoodsBean.class);
                    Gson gson = new Gson();
                    BaseGoods base = gson.fromJson(response.toString(), BaseGoods.class);
                    ArrayList<GoodsBean> list = base.getData();
                    DataSupport.saveAll(list);
                }
            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(), "获取商品信息失败，请重新获取",
                        Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable e) {
            super.onFailure(statusCode, headers, responseBody, e);
            MyShowDialog.closeLoadingDialog();
            Log.e("lh", " getGoods==" + statusCode);
            Log.e("lh", " getGoods==" + responseBody);
            Toast.makeText(getApplicationContext(), "网络请求超时，请重新获取",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private class JsonPushBuy extends JsonHttpResponseHandler {

        @Override
        public void onStart() {
            super.onStart();
            MyShowDialog.showLoadingDialog(UrgentSetActivity.this, "数据上传中.");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
//            Log.e("lh", "JsonPushMakemeal=="+response.toString());
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    ContentValues values = new ContentValues();
                    values.put("submit", 1);
                    DataSupport.updateAll(UserBuyBean.class, values, "submit=?", "0");
                } else {

                }
                Toast.makeText(getApplicationContext(), msg,
                        Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {

                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable e) {
            super.onFailure(statusCode, headers, responseBody, e);
            MyShowDialog.closeLoadingDialog();
            Log.e("lh", " pullstatusCode==" + statusCode);
            Log.e("lh", " pullresponseBody==" + responseBody);
            Toast.makeText(getApplicationContext(), "网络请求超时，请重新提交",
                    Toast.LENGTH_SHORT).show();
        }
    }
}
